<?php

namespace App\Imports;

use App\Common\statement\CommonStatement;
use App\Exceptions\api\BaseException;
use App\Models\exams\Question;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Concerns\ToCollection;
use Illuminate\Support\Collection;

class QuestionImport implements ToCollection
{

    public function collection(collection $rows)
    {
        $question_type = array_flip(CommonStatement::question_type);
        $question_cate = array_flip(CommonStatement::question_cate);
        DB::beginTransaction();
        try{
            foreach ($rows as $k => $row){
                if ($k != 0){//跳过表头
                    if(!isset($question_type[$row[0]])){
                        throw new BaseException('导入失败:数据错误');
                    }
                    if(!isset($question_cate[$row[2]])){
                        throw new BaseException('导入失败:数据错误');
                    }
                    if($question_type[$row[0]] == 2 && count(explode(',',$row[9])) < 2){
                        throw new BaseException('导入失败:数据错误');
                    }
                    $question = [
                        'type' => $question_type[$row[0]],
                        'title' => $row[1],
                        'cate' => $question_cate[$row[2]],
                        'A' => $row[3],
                        'B' => $row[4],
                        'C' => $row[5],
                        'D' => $row[6],
                        'E' => $row[7],
                        'F' => $row[8],
                        'answer' => $row[9],
                        'score' => $row[10],
                        'analysisi' => $row[11]
                    ];

                    $add = Question::create($question);
                    if(!$add){
                        DB::rollBack();
                        throw new BaseException('导入失败:系统错误');
                    }
                }
            }
            DB::commit();
        }catch (\Exception $e){
            DB::rollBack();
            throw new BaseException($e->getMessage());
        }

    }
}